package com.panda.pandawash.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.panda.pandawash.bean.BindDevicesBean;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.panda.pandawash.R;
import com.panda.pandawash.activity.MotorMonitorActivity;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.model.MotorDeviceInfoMessage;
import com.panda.pandawash.model.MotorStatusMessage;
import com.panda.pandawash.util.SelfDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by gaowf on 2017/2/25.
 */

public class MonitorSettingFragment extends Fragment {
    private String TAG = "MonitorFactoryFragment";

    private byte[] cmd0 = { (byte) 0xa0, 0x00, 0x01, (byte) 0xc0, 0x00 };
    private byte[] cmd1 = { (byte) 0xa0, 0x00, 0x02, (byte) 0xc0, 0x00 };
    private byte[] cmd2 = { (byte) 0xa0, 0x00, 0x03, (byte) 0xc0, 0x00 };
    private byte[] cmd3 = { (byte) 0xa0, 0x00, 0x04, (byte) 0xc0, 0x00 };
    private byte[] cmd4 = { (byte) 0xa0, 0x00, 0x05, (byte) 0xc0, 0x00 };
    private byte[] cmd5 = { (byte) 0xa0, 0x00, 0x06, (byte) 0xc0, 0x00 };
    private byte[] cmd6 = { (byte) 0xa0, 0x00, 0x07, (byte) 0xc0, 0x00 };
    private byte[] cmd7 = { (byte) 0xa0, 0x00, 0x08, (byte) 0xc0, 0x00 };
    private byte[] cmd8 = { (byte) 0xa0, 0x00, 0x09, (byte) 0xc0, 0x00 };
    private byte[] cmd9 = { (byte) 0xa0, 0x00, 0x0A, (byte) 0xc0, 0x00 };
    private byte[] cmd10 = { (byte) 0xa0, 0x00, 0x0B, (byte) 0xc0, 0x00 };
    private byte[] cmd11 = { (byte) 0xa0, 0x00, 0x0C, (byte) 0xc0, 0x00 };
    private byte[] cmd12 = { (byte) 0xa0, 0x00, 0x0D, (byte) 0xc0, 0x00 };
    private byte[] cmd13 = { (byte) 0xa0, 0x00, 0x0E, (byte) 0xc0, 0x00 };
    private byte[] cmd14 = { (byte) 0xa0, 0x00, 0x0F, (byte) 0xc0, 0x00 };
    private byte[] cmd15 = { (byte) 0xa0, 0x00, 0x10, (byte) 0xc0, 0x00 };
    private byte[] cmd16 = { (byte) 0xa0, 0x00, 0x11, (byte) 0xc0, 0x00 };
    private byte[] cmd17 = { (byte) 0xa0, 0x00, 0x12, (byte) 0xc0, 0x00 };
    private byte[] cmd25 = { (byte) 0xa0, 0x00, 0x25, (byte) 0xc0, 0x00 };
    private byte[] cmd26 = { (byte) 0xa0, 0x00, 0x26, (byte) 0xc0, 0x00 };
    private byte[] cmd27 = { (byte) 0xa0, 0x00, 0x27, (byte) 0xc0, 0x00 };
    private byte[] cmd28 = { (byte) 0xa0, 0x00, 0x28, (byte) 0xc0, 0x00 };

    private byte[] cmd2F = { (byte) 0xa0, 0x01, 0x2F, (byte) 0xC0, 0x70 };
    //private byte[] cmd61 = { (byte) 0xa0, 0x00, 0x0E, (byte) 0xC0, 0x4E };

    private EditText mShutGunDelayEditText;
    private Button mShutGunDelayButton;

    private EditText mOpenGunDelayEditText;
    private Button mOpenGunDelayButton;

    private EditText mShutDownMotorDelayEditText;
    private Button mShutDownMotorDelayButton;

    private EditText mMotorMaxRuningEditText;
    private Button mMotorMaxRuningButton;

    private RadioGroup mMotorStyleGroup1;
    private RadioGroup mMotorStyleGroup2;

    private RadioButton mMotorKeepoffButton;
    private RadioButton mMotorKeeponButton;
    private RadioButton mMotorKeepwirelessButton;

    private LinearLayout mMotorSettingLinearLayout;

    private LinearLayout mViewDevicePetName;
    private LinearLayout mViewPowerOffTime;
    private LinearLayout mViewGunOffTime;
    private LinearLayout mViewAutoOffTime;
    private LinearLayout mViewRunningOnTime;
    private LinearLayout mViewSwitchStatus;
    private SelfDialog mSelfDialog;

    private TextView sgdelayTextView;
    private TextView ogdelayTextView;
    private TextView sjdelayTextView;
    private TextView xcjdelayTextView;

    private TextView switchStatusTextView;

    private RadioGroup mRadioGroup;
    private RadioButton radioBtnAlwaysOff;
    private RadioButton radioBtnAlwaysOn;
    private RadioButton radioBtnBleSet;
    private RadioButton radioBtnManualSet;

    private final String ALWAYS_Off = "常闭";
    private final String ALWAYS_ON = "常开";
    private final String BLE_SET = "无线";
    private final String MANUAL_SET = "手动";

    public final static String COMMAND_ECHO = "command_echo";
    public final static String DEVICE_NAME = "device_name";
    public final static int COMMAND_ECHO_CODE = 0x10;
    public final static String MONITOR_SETTING_INFO = "monitor_setting_info";
    public final static String MONITOR_USER_INFO = "monitor_user_info";
    public final static int UPDATE_SETTING_INFO = 0x20;

    public final static String SETTING_INFO = "setting_info";
    public final static String SETTING_STATUS = "setting_status";

    private boolean isSet = true;
    private boolean isShow = true;

    private TextView devicePetName;

    private String myDeviceName;
    private String myDeviceMacAddress;
    private int myDeviceModel;
    private String myDevicePetName;


    private long sendCmdTime;

    private ToggleButton mtoggleButton;
    private boolean initcheck=true;
    private boolean cancelclick=false;
    private boolean hasRecvResp = false;
    private ProgressDialog mPd;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View fragmentView = inflater.inflate(R.layout.monitor_factory_layout,
                container, false);
        initViews(fragmentView);

        return fragmentView;
    }


    private void initViews(View fragmentView ){

        mRadioGroup = (RadioGroup) fragmentView
                .findViewById(R.id.radio_group_device_states);
        radioBtnAlwaysOff = (RadioButton) fragmentView
                .findViewById(R.id.radio_btn_always_off);
        radioBtnAlwaysOn = (RadioButton) fragmentView
                .findViewById(R.id.radio_btn_always_on);
        radioBtnBleSet = (RadioButton) fragmentView
                .findViewById(R.id.radio_btn_ble_set);
        radioBtnManualSet = (RadioButton) fragmentView
                .findViewById(R.id.radio_btn_manual_set);
        mRadioGroup.setOnCheckedChangeListener(radioChange);

        devicePetName = (TextView) fragmentView
                .findViewById(R.id.device_pet_name);
        sgdelayTextView = (TextView) fragmentView.findViewById(R.id.sgdelay);
        ogdelayTextView = (TextView) fragmentView.findViewById(R.id.ogdelay);
        sjdelayTextView = (TextView) fragmentView
                .findViewById(R.id.sjautodelay);
        xcjdelayTextView = (TextView) fragmentView.findViewById(R.id.cxdelay);
        switchStatusTextView = (TextView) fragmentView
                .findViewById(R.id.switch_status);

        mShutGunDelayEditText = (EditText) fragmentView
                .findViewById(R.id.monitor_factory_shut_gun_delay_edittext);
        mShutGunDelayButton = (Button) fragmentView
                .findViewById(R.id.monitor_factory_shut_gun_delay_button);

        mShutDownMotorDelayButton = (Button) fragmentView
                .findViewById(R.id.monitor_factory_shut_motor_delay_button);
        mShutDownMotorDelayEditText = (EditText) fragmentView
                .findViewById(R.id.monitor_factory_shut_motor_delay_edittext);

        mMotorMaxRuningButton = (Button) fragmentView
                .findViewById(R.id.monitor_factory_motor_max_delay_button);
        mMotorMaxRuningEditText = (EditText) fragmentView
                .findViewById(R.id.monitor_factory_motor_max_delay_edittext);

        mOpenGunDelayButton = (Button) fragmentView
                .findViewById(R.id.monitor_factory_open_gun_delay_button);
        mOpenGunDelayEditText = (EditText) fragmentView
                .findViewById(R.id.monitor_factory_open_gun_delay_edittext);

        mMotorSettingLinearLayout = (LinearLayout) fragmentView
                .findViewById(R.id.monitor_layout_setting_iref);

        mViewDevicePetName = (LinearLayout) fragmentView
                .findViewById(R.id.view_device_pet_name);
        mViewPowerOffTime = (LinearLayout) fragmentView
                .findViewById(R.id.view_gun_off_time);
        mViewGunOffTime = (LinearLayout) fragmentView
                .findViewById(R.id.view_gun_on_time);
        mViewAutoOffTime = (LinearLayout) fragmentView
                .findViewById(R.id.view_auto_off_time);
        mViewRunningOnTime = (LinearLayout) fragmentView
                .findViewById(R.id.view_running_on_time);
        mViewSwitchStatus = (LinearLayout) fragmentView
                .findViewById(R.id.view_switch_status);

        SharedPreferences mSharedPreferences = getActivity()
                .getSharedPreferences("init", Activity.MODE_PRIVATE);
        String name = mSharedPreferences.getString("auth", "OFF");

        if (name.equals("ON")) {
            mMotorSettingLinearLayout.setVisibility(View.VISIBLE);
        } else {
            mMotorSettingLinearLayout.setVisibility(View.GONE);
        }

        mShutDownMotorDelayButton.setOnClickListener(mOnClickListener);
        mShutGunDelayButton.setOnClickListener(mOnClickListener);
        mMotorMaxRuningButton.setOnClickListener(mOnClickListener);
        mOpenGunDelayButton.setOnClickListener(mOnClickListener);

        mViewDevicePetName.setOnClickListener(mOnClickListener);
        mViewPowerOffTime.setOnClickListener(mOnClickListener);
        mViewGunOffTime.setOnClickListener(mOnClickListener);
        mViewAutoOffTime.setOnClickListener(mOnClickListener);
        mViewRunningOnTime.setOnClickListener(mOnClickListener);
        mViewSwitchStatus.setOnClickListener(mOnClickListener);

        mMotorStyleGroup1 = (RadioGroup) fragmentView
                .findViewById(R.id.monitor_factory_ragiog1);
        mMotorStyleGroup2 = (RadioGroup) fragmentView
                .findViewById(R.id.monitor_factory_ragiog2);

        mMotorKeepoffButton = (RadioButton) fragmentView
                .findViewById(R.id.monitor_factory_keepoff);
        mMotorKeeponButton = (RadioButton) fragmentView
                .findViewById(R.id.monitor_factory_keepon);
        mMotorKeepwirelessButton = (RadioButton) fragmentView
                .findViewById(R.id.monitor_factory_wearlless);

        mMotorStyleGroup1.setOnCheckedChangeListener(mOnCheckedChangeListener);
        mMotorStyleGroup2.setOnCheckedChangeListener(mOnCheckedChangeListener);
        mPd=new ProgressDialog(getActivity());
        mPd.setMessage("请等待...");
        mtoggleButton=(ToggleButton)fragmentView.findViewById(R.id.delay_shut_down_toggle);
        mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);
        mMotorStyleGroup2.clearCheck();

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        Log.i("bear_", "Factory's Resume!");
    }

    public void setInfoAndStatus(MotorDeviceInfoMessage infoMessage, MotorStatusMessage statusMessage) {
        Log.i(TAG, "setInfoAndStatus--1--sendCmdTime is " + sendCmdTime);
        if (!initcheck/* || SystemClock.elapsedRealtime() - sendCmdTime < 2000*/) {
            return;
        }

        sgdelayTextView.setText(String.valueOf(infoMessage.getsgDelay()));
        ogdelayTextView.setText(String.valueOf(infoMessage.getogDelay()));
        xcjdelayTextView.setText(String.valueOf(infoMessage
                .getMaxContinueRuningTime()));
        //mPd.hide();
        sjdelayTextView.setText(String.valueOf(infoMessage.getsjdelayTime()));
        mtoggleButton.setOnCheckedChangeListener(null);
        //if(initcheck){
        if(infoMessage.getsjdelayTime().equals("不启用")){
            mtoggleButton.setChecked(false);
        }else{
            mtoggleButton.setChecked(true);
        }
        //initcheck=false;
        //}
        mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);
        String status = infoMessage.getstartUpMethod();

        infoMessage.setDeviceStatus(status);
        // Log.i("bear__", "+++++++++" + status);

        //Log.d(TAG, "setInfoAndStatus--status is " + status);

        if (status.equals(ALWAYS_Off)) {

            switchStatusTextView.setText("开启");

        } else if (status.equals(ALWAYS_ON)) {

            switchStatusTextView.setText("开启");

        } else if (status.equals(BLE_SET)) {

            switchStatusTextView.setText("开启");

        } else {
            switchStatusTextView.setText("关闭");

        }

    }

    public void  updateInfoAndStatus(Intent data){
        if (!initcheck) {
            return;
        }

        String monitorSettingString = data.getStringExtra(MONITOR_SETTING_INFO);
        String mDeviceName = data.getStringExtra(DEVICE_NAME);

        Message message = new Message();
        message.what = UPDATE_SETTING_INFO;
        Bundle bundle = new Bundle();

        bundle.putString(MONITOR_SETTING_INFO, monitorSettingString);
        bundle.putString(MONITOR_USER_INFO, mDeviceName);
        message.setData(bundle);
        mHandler.sendMessage(message);

    }

    private CompoundButton.OnCheckedChangeListener mToggleButtonListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(cancelclick){
                cancelclick=false;
                //return;
            }

            if(isChecked==true/* && initcheck==false*/) {
                showDialog1(
                        R.id.view_auto_off_time,
                        null,
                        (InputType.TYPE_CLASS_NUMBER/* | InputType.TYPE_NUMBER_FLAG_DECIMAL*/),
                        "时间设置", "分", sjdelayTextView.getText().toString().equals("不启用")?"":sjdelayTextView.getText().toString());
                mSelfDialog.setCancelable(false);
            }else if(isChecked==false/* && initcheck==false*/){
                setToDevices(R.id.view_auto_off_time, 0.0);
            }

        }
    };

    private RadioGroup.OnCheckedChangeListener radioChange = new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.radio_btn_always_off:
                    showDeviceSetDialog(0, ALWAYS_Off, 0);

                    break;
                case R.id.radio_btn_always_on:
                    showDeviceSetDialog(0, ALWAYS_ON, 1);

                    break;
                case R.id.radio_btn_ble_set:
                    showDeviceSetDialog(0, BLE_SET, 2);

                    break;
                case R.id.radio_btn_manual_set:
                    showDeviceSetDialog(0, MANUAL_SET, 3);
                    break;

                default:
				//MotorMonitorActivity mMotorMonitorActivity5 = (MotorMonitorActivity) getActivity();
                    if (MotorMonitorActivity.getInstance() == null) {
                        Log.d("hys123","MotorMonitorActivity.getInstance() == null");
                        return;
                    }
                    cmd13[1] = (byte) 0;
                    MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd13));

				break;
			}
		}
	};

    private void showDeviceSetDialog(final int i, String style,
                                     final int input_type) {
        mSelfDialog = new SelfDialog(getActivity());
        Window mWindow = mSelfDialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.TOP);
        lp.y = 300;// 设置竖直偏移量

        mSelfDialog.setTitle("确认是否设置为" + "“" + style + "”");

        mSelfDialog.setEditVisibility(View.GONE);

        mSelfDialog.setYesOnclickListener("确定",
                new SelfDialog.onYesOnclickListener() {

                    @Override
                    public void onYesClick(Object data, boolean flg) {
                        if (MotorMonitorActivity.getInstance() == null) {
                            Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                            return;
                        }
						cmd13[1] = (byte) input_type;
                        MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd13));
						mSelfDialog.dismiss();
					}
				});
		mSelfDialog.setNoOnclickListener("取消",
				new SelfDialog.onNoOnclickListener() {
					@Override
					public void onNoClick() {
						// Toast.makeText(getActivity(), "点击了--取消--按钮",
						// Toast.LENGTH_LONG).show();
						mSelfDialog.dismiss();
					}
				});

        mSelfDialog.show();

    }

    private void SetStatusDialog(String statusName, final int status) {
        mSelfDialog = new SelfDialog(getActivity());
        Window mWindow = mSelfDialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.CENTER);

        mSelfDialog.setTitle("确认是否设置" + "”" + statusName + "”？");
        mSelfDialog.setMessage("确认是否设置" + "”" + statusName + "”？");
        mSelfDialog.setEditVisibility(View.GONE);
        mSelfDialog.setYesOnclickListener("确定",
                new SelfDialog.onYesOnclickListener() {

                    @Override
                    public void onYesClick(Object data, boolean flg) {
                        // TODO Auto-generated method stub

                        if (MotorMonitorActivity.getInstance() == null) {
                            Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                            return;
                        }
						cmd13[1] = (byte) status;
                        MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd13));
						mSelfDialog.dismiss();
					}
				});
		mSelfDialog.setNoOnclickListener("取消",
				new SelfDialog.onNoOnclickListener() {
					@Override
					public void onNoClick() {

                        mSelfDialog.dismiss();
                    }
                });
        mSelfDialog.show();
    }

    OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub

            if (group == mMotorStyleGroup1) {

                switch (checkedId) {
                    case R.id.monitor_factory_keepoff:
                        Log.i(TAG, " GROUP1 keep off " + checkedId);
                        if (mMotorKeepoffButton.isChecked()) {
                            mMotorStyleGroup2.clearCheck();
                        }
                        break;
                    case R.id.monitor_factory_keepon:
                        Log.i(TAG, " GROUP1 keep on " + checkedId);
                        if (mMotorKeeponButton.isChecked()) {
                            mMotorStyleGroup2.clearCheck();
                        }
                        break;
                    default:
                        break;
                }

            } else {

                Log.i(TAG, " GROUP2 " + checkedId);
                switch (checkedId) {
                    case R.id.monitor_factory_wearlless:
                        Log.i(TAG, " GROUP2 wireless " + checkedId);
                        if (mMotorKeepwirelessButton.isChecked()) {
                            mMotorStyleGroup1.clearCheck();
                        }

                        break;

                    default:
                        break;
                }
            }

        }
    };

    OnCheckedChangeListener mOnCheckedChangeListener1 = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub

            if (group == mMotorStyleGroup1) {

                mMotorStyleGroup2.clearCheck();
            }

            if (group == mMotorStyleGroup2) {

                mMotorStyleGroup1.clearCheck();
            }

        }
    };

    OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

			switch (v.getId()) {
			case R.id.monitor_factory_motor_max_delay_button: {

                if (MotorMonitorActivity.getInstance() == null) {
                    Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                    return;
                }

				String delaytime = mMotorMaxRuningEditText.getText().toString();

				int delay = Integer.valueOf(delaytime);
				cmd26[1] = (byte) delay;

                MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd26));
			}

				break;

			case R.id.monitor_factory_open_gun_delay_button: {
                if (MotorMonitorActivity.getInstance() == null) {
                    Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                    return;
                }

				String delaytime = mOpenGunDelayEditText.getText().toString();

				float delay = Float.valueOf(delaytime);

				delay = delay * 10;

				cmd28[1] = (byte) delay;

                MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd28));
			}

				break;

			case R.id.monitor_factory_shut_gun_delay_button: {
                if (MotorMonitorActivity.getInstance() == null) {
                    Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                    return;
                }


				String delaytime = mShutGunDelayEditText.getText().toString();

				float delay = Float.valueOf(delaytime);
				cmd10[1] = (byte) delay;

                MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd10));
			}

				break;

			case R.id.monitor_factory_shut_motor_delay_button: {
                if (MotorMonitorActivity.getInstance() == null) {
                    Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                    return;
                }

				String delaytime = mShutDownMotorDelayEditText.getText()
						.toString();

				float delay = Float.valueOf(delaytime);
				cmd11[1] = (byte) delay;

                MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd11));
			}
				break;

			case R.id.view_device_pet_name:
				showDialog(R.id.view_device_pet_name, null,
						InputType.TYPE_CLASS_TEXT, "昵称设置", null, devicePetName
								.getText().toString());


				break;

			case R.id.view_gun_off_time:
				showDialog(R.id.view_gun_off_time, null,
						InputType.TYPE_CLASS_NUMBER, "时间设置", "秒",
						sgdelayTextView.getText().toString());
				break;

                case R.id.view_gun_on_time:
                    showDialog(
                            R.id.view_gun_on_time,
                            null,
                            (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL),
                            "时间设置", "秒", ogdelayTextView.getText().toString());
                    Log.d("hys123","sgdelayTextView " + ogdelayTextView.getText().toString());

                    break;

                case R.id.view_auto_off_time:
                    //showDialog(
                    //        R.id.view_auto_off_time,
                    //        null,
                    //        (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL),
                    //        "时间设置", "分钟", sjdelayTextView.getText().toString());
                    break;

                case R.id.view_running_on_time:
                    showDialog(
                            R.id.view_running_on_time,
                            null,
                            (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL),
                            "时间设置", "分钟", xcjdelayTextView.getText().toString());
                    Log.d("hys123","xcjdelayTextView " + xcjdelayTextView.getText().toString());

                    break;

                case R.id.view_switch_status:
                    choseRadioButton();
                    break;

                default:
                    break;
            }

        }

    };

    private void choseRadioButton() {
        final String[] method = new String[] { "关闭", "开启" };

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());// 自定义对话框
        builder.setTitle("关枪停机功能");
        int selectBtn = 0;
        if (MotorDeviceInfoMessage.getDeviceStatus().equals(ALWAYS_Off)) {
            selectBtn = 1;

        } else if (MotorDeviceInfoMessage.getDeviceStatus().equals(ALWAYS_ON)) {

            selectBtn = 1;

        } else if (MotorDeviceInfoMessage.getDeviceStatus().equals(BLE_SET)) {

            selectBtn = 1;

        } else {
            selectBtn = 0;
        }

        // Log.i("bear__", "~~~~~~~~~~~~~" + selectBtn);

        builder.setSingleChoiceItems(method, selectBtn,
                new DialogInterface.OnClickListener() {// 2默认的选中

                    @Override
                    public void onClick(DialogInterface dialog, int which) {// which是被选中的位置
                        // 点击关闭时发送0x80 0x01 0x2F 0xC0 0x70;
                        // 点击开启时发送0x80 0x00 0x0E 0xC0 0x4E;
                        // Log.i("bear__", "_____________`whitch =  " + which);

                        if (MotorMonitorActivity.getInstance() == null) {
                            Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                            return;
                        }
						if (which == 1) {
                            MotorMonitorActivity.getInstance()
                                    .send_msg_to_motor_and_update_info(generateCRCCode(cmd13));
							Log.i("bear__", "~~~~~~~~`cmd61 = " + cmd13
									+ "-------" + generateCRCCode(cmd13));
						} else {
                            MotorMonitorActivity.getInstance()
                                    .send_msg_to_motor_and_update_info(generateCRCCode(cmd2F));
							// Log.i("bear__", "~~~~~~~~`whitch =  0");
						}

                        // switchStatusTextView.setText(method[which]);
                        Toast.makeText(getActivity(), "正在设置,请稍后",
                                Toast.LENGTH_LONG).show();
                        dialog.dismiss();

                        // 随便点击一个item消失对话框，不用点击确认取消
                    }
                });
        builder.show();// 让弹出框显示

    }

    byte[] generateCRCCode(byte[] cmd) {

        byte result = 0;
        byte[] newcmd = new byte[cmd.length];

        for (int i = 0; i < cmd.length - 1; i++) {
            newcmd[i] = cmd[i];
            result ^= (cmd[i] & 0xff);
        }
        newcmd[cmd.length - 1] = (byte) (result & 0xff);
        return newcmd;
    }

    private void showDialog1(final int i, String digits, int input_type,
                             String title, final String unit, String value) {
        if (mSelfDialog != null) {
            mSelfDialog.dismiss();
            mSelfDialog = null;
        }
        mSelfDialog = new SelfDialog(getActivity());
        Window mWindow = mSelfDialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.TOP);
        lp.y = 300;// 设置竖直偏移量

        mSelfDialog.setTitle(title);
        mSelfDialog.setMessage("确定退出应用?");

        mSelfDialog.setEditDigits(digits);
        mSelfDialog.setEditType(input_type);

        mSelfDialog.setEditText(value);

		/*
		 * if (i == R.id.view_auto_off_time || i == R.id.view_running_on_time) {
		 * mSelfDialog.setUinit("分钟"); }
		 */
        if (unit == null) {
            mSelfDialog.setUnitLayoutVisibility(View.GONE);
        } else {
            mSelfDialog.setUinit(unit);
        }

        initcheck = false;

        mSelfDialog.setYesOnclickListener("确定",
                new SelfDialog.onYesOnclickListener() {

                    @Override
                    public void onYesClick(Object data, boolean flg) {
                        // TODO Auto-generated method stub
                        // Toast.makeText(getActivity(), "点击了--确定--按钮",
                        // Toast.LENGTH_LONG).show();
                        initcheck = true;
                        if (unit == null) {

                            if (data.toString().equals("-1")) {
                                Toast.makeText(getActivity(), "昵称为空",
                                        Toast.LENGTH_LONG).show();
                            } else {
                                updateDevicePetName(data.toString());
                                devicePetName.setText(data.toString());
                            }

                        } else {
                            if(data.toString().equals("不启用")){
                                setToDevices(i, 0);
                                mtoggleButton.setOnCheckedChangeListener(null);
                                mtoggleButton.setChecked(false);
                                mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);
                            }else {
                                int time = Integer.parseInt(data.toString());
                                if (time <= 0 || time > 255) {
                                    Toast.makeText(getActivity(),
                                            "时间设置区间(1~255)",
                                            Toast.LENGTH_LONG).show();
                                    return;

                                }

                                Log.e("lubo", "time:" + time);
                                setToDevices(i, time);
                            }
                        }

                        mSelfDialog.dismiss();
                    }
                });
        mSelfDialog.setNoOnclickListener("取消",
                new SelfDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        initcheck = true;
                        mSelfDialog.dismiss();
                        cancelclick=true;
                        mtoggleButton.setOnCheckedChangeListener(null);
                        mtoggleButton.setChecked(!mtoggleButton.isChecked());
                        mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);
                    }
                });

        mSelfDialog.show();

    }

    private void showDialog(final int i, String digits, int input_type,
                            String title, final String unit, String value) {
        mSelfDialog = new SelfDialog(getActivity());
        Window mWindow = mSelfDialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.TOP);
        lp.y = 300;// 设置竖直偏移量

        mSelfDialog.setTitle(title);
        mSelfDialog.setMessage("确定退出应用?");

        mSelfDialog.setEditDigits(digits);
        mSelfDialog.setEditType(input_type);

        mSelfDialog.setEditText(value);

        if (unit == null) {
            mSelfDialog.setUnitLayoutVisibility(View.GONE);
        } else {
            mSelfDialog.setUinit(unit);
        }

        mSelfDialog.setYesOnclickListener("确定",
                new SelfDialog.onYesOnclickListener() {

                    @Override
                    public void onYesClick(Object data, boolean flg) {
                        // TODO Auto-generated method stub
                        if (unit == null) {

                            if (data.toString().equals("-1")) {
                                Toast.makeText(getActivity(), "昵称为空",
                                        Toast.LENGTH_LONG).show();
                            } else {
                                updateDevicePetName(data.toString());
                                devicePetName.setText(data.toString());

                                MotorMonitorActivity.getInstance().send_msg_to_updateToolar(data.toString());

                            }

                        } else {
                            double time = Double.parseDouble(data.toString());
                            if (time == -1) {
                                Toast.makeText(getActivity(), "时间未修改",
                                        Toast.LENGTH_LONG).show();
                                return;
                            } else {

                                if (i == R.id.view_gun_on_time) {
                                    if (time < 0 || time > 25.5) {
                                        Toast.makeText(getActivity(),
                                                "时间设置区间(0~25.5)",
                                                Toast.LENGTH_LONG).show();
                                        return;
                                    }

                                } else {
                                    if (time < 0 || time > 255) {

                                        Toast.makeText(getActivity(),
                                                "时间设置区间(0~255)",
                                                Toast.LENGTH_LONG).show();
                                        return;

                                    }

                                }
                            }
                            setToDevices(i, time);
                        }

                        mSelfDialog.dismiss();
                    }
                });
        mSelfDialog.setNoOnclickListener("取消",
                new SelfDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        mSelfDialog.dismiss();
                    }
                });

        mSelfDialog.show();

    }

    private void findDevicePetName() {
        String macString = CDApplication.getIntance().getUserMAC();

        Log.i("bear_", "macString = " + macString);
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
        try {
            BindDevicesBean deviceQuery = dbUtils
                    .findFirst(Selector.from(BindDevicesBean.class).where(
                            "mac_address", "=", macString));
            if(deviceQuery != null) {
                myDeviceModel = deviceQuery.getModel();
                myDeviceName = deviceQuery.getName();
                myDeviceMacAddress = deviceQuery.getMacAddress();
                myDevicePetName = deviceQuery.getPedName();
            }
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i("bear_", "myDeviceModel = " + myDeviceModel
                + "-------myDeviceName = " + myDeviceName
                + "---------myDeviceMacAddress = " + myDeviceMacAddress
                + "----------myDevicePetName = " + myDevicePetName);
    }

    private void updateDevicePetName(String petName) {
        findDevicePetName();

        BindDevicesBean bindDevicesBean = new BindDevicesBean();
        bindDevicesBean.setModel(myDeviceModel);
        bindDevicesBean.setName(myDeviceName);
        bindDevicesBean.setMacAddress(myDeviceMacAddress);
        bindDevicesBean.setPetName(petName);

        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();

        try {
            dbUtils.update(bindDevicesBean,
                    WhereBuilder.b("mac_address", "=", myDeviceMacAddress),
                    "name", "pet_name");
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

	private void setToDevices(int i, double time) {
		switch (i) {
		case R.id.view_gun_off_time:

			//MotorMonitorActivity mMotorMonitorActivity1 = (MotorMonitorActivity) getActivity();
            if(MotorMonitorActivity.getInstance() == null) {
                Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                return;
            }
            float delay1 = Float.valueOf((float) time);
			cmd10[1] = (byte) delay1;
			// sgdelayTextView.setText(String.valueOf(delay1));
            MotorMonitorActivity.getInstance() .send_msg_to_motor_and_update_info(generateCRCCode(cmd10));

			break;

		case R.id.view_gun_on_time:
            if(MotorMonitorActivity.getInstance() == null) {
                Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                return;
            }
			float delay2 = Float.valueOf((float) time);
			// ogdelayTextView.setText(String.valueOf(delay2));
			delay2 = delay2 * 10;
			cmd28[1] = (byte) delay2;

            MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd28));

			break;

		case R.id.view_auto_off_time:
            if(MotorMonitorActivity.getInstance() == null) {
                Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                return;
            }
			float delay3 = Float.valueOf((float) time);
			cmd11[1] = (byte) delay3;
			// sjdelayTextView.setText(String.valueOf(delay3));
            MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd11));
			//sendCmdTime = SystemClock.elapsedRealtime();
			break;

		case R.id.view_running_on_time:
            if(MotorMonitorActivity.getInstance() == null) {
                Log.d("hys123", "MotorMonitorActivity.getInstance() == null");
                return;
            }
			int delay = Integer.valueOf((int) time);
			cmd26[1] = (byte) delay;
			// xcjdelayTextView.setText(String.valueOf(delay));
            MotorMonitorActivity.getInstance().send_msg_to_motor_and_update_info(generateCRCCode(cmd26));

                break;

            default:
                break;
        }
        hasRecvResp = false;
        showWaitDialog();
    }

    private Timer mTimer;
    private Handler mTimerHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    hideWaitDialog();
                    if (!hasRecvResp) {
                        Toast.makeText(getActivity(), "设置失败，请稍候重试", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    private void showWaitDialog() {
        initcheck = false;
        mPd.show();

        if (mTimer != null) {
            mTimer.cancel();
        }
        mTimer = new Timer();
        TimerTask mTimerTask = new TimerTask() {
            public void run() {
                mTimerHandler.sendEmptyMessage(1);
            }
        };
        mTimer.schedule(mTimerTask, 6000, 1000);
    }

    private void hideWaitDialog() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        mPd.hide();
        initcheck = true;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        switch (resultCode) {
            case COMMAND_ECHO_CODE: {
                updateInfoAndStatus(data);
                byte[] echo = data.getByteArrayExtra(COMMAND_ECHO);
                Message message = new Message();
                message.what = COMMAND_ECHO_CODE;
                Bundle bundle = new Bundle();
                bundle.putByteArray(COMMAND_ECHO, echo);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
            break;

            default:
                break;
        }

    }

    Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

            switch (msg.what) {
                case COMMAND_ECHO_CODE:
                    byte[] echo = msg.getData().getByteArray(COMMAND_ECHO);
                    if (echo != null) {
                        Log.d("hys123","MonitorSettingFragment handleMessage  echo == "+ echo);
                        handle_command_echo(echo);
                    }

                    break;
                case UPDATE_SETTING_INFO:
                    String settinginfo = msg.getData().getString(MONITOR_SETTING_INFO);
                    String username = msg.getData().getString(MONITOR_USER_INFO);
                    Log.e("hys123","settinginfo == "+ settinginfo + " username "+ username);
                    if(settinginfo !=null && username != null) {
                        try {
                            JSONObject object = new JSONObject(settinginfo);


                            String motor_shutgun_delayString = object.getString(MotorDeviceInfoMessage.MOTOR_SHUTGUN_DELAY_VALUE);
                            String motor_startgun_delayString = object.getString(MotorDeviceInfoMessage.MOTOR_STARTGUN_DELAY_VALUE);
                            String motor_max_continue_runString = object.getString(MotorDeviceInfoMessage.MOTOR_MAX_CONTINUE_RUN_VALUE);
                            String motor_sj_delayString = object.getString(MotorDeviceInfoMessage.MOTOR_SJ_DELAY_VALUE);

                            sgdelayTextView.setText(motor_shutgun_delayString);
                            ogdelayTextView.setText(motor_startgun_delayString);
                            xcjdelayTextView.setText(motor_max_continue_runString);
                            sjdelayTextView.setText(motor_sj_delayString);
                            updateDeviceName(username);
                            mtoggleButton.setOnCheckedChangeListener(null);
                            if (motor_sj_delayString.equals("不启用")) {
                                mtoggleButton.setChecked(false);
                            } else {
                                mtoggleButton.setChecked(true);
                            }
                            mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);

                            String status = object.getString(MotorDeviceInfoMessage.MOTOR_STARTUP_METHOD_VALUE);
                            if (status.equals(ALWAYS_Off)) {

                                switchStatusTextView.setText("开启");

                            } else if (status.equals(ALWAYS_ON)) {

                                switchStatusTextView.setText("开启");

                            } else if (status.equals(BLE_SET)) {

                                switchStatusTextView.setText("开启");

                            } else {
                                switchStatusTextView.setText("关闭");

                            }


                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    break;
                default:
                    break;
            }

        };
    };

    private void handle_command_echo(byte[] echo) {

        Log.d("hys123","MonitorSettingFragment handle_command_echo echo "+echo);
        if(echo[1] != 7) {
            Log.d("hys123","MonitorSettingFragment handle_command_echo echo[1] "+echo[1]);
            return;
        }
        Log.i("hys123", "MonitorSettingFragmenthandle_command_echo--echo[2] is " + echo[2]);
        sendCmdTime = SystemClock.elapsedRealtime();
        hasRecvResp = true;
        if (mPd != null) {
            mPd.hide();
        }


        switch (echo[2]) {
            case 0x0B://cmd10[2]:
                sgdelayTextView.setText((String.valueOf( echo[3] & 0xff)));
                break;

            case 0x0C://cmd11[2]
                mtoggleButton.setOnCheckedChangeListener(null);
                if (echo[3] != 0) {
                    sjdelayTextView.setText((String.valueOf(echo[3] & 0xff)));
                    mtoggleButton.setChecked(true);
                }
                else {
                    sjdelayTextView.setText("不启用");
                    mtoggleButton.setChecked(false);
                }
                mtoggleButton.setOnCheckedChangeListener(mToggleButtonListener);
                break;

            case 0x28://cmd28[1]
                ogdelayTextView.setText((String.valueOf( (echo[3] & 0xff)/10.0)));
                break;

            case 0x26://cmd26[1]
                xcjdelayTextView.setText((String.valueOf( (echo[3] & 0xff)/10.0)));
                break;

            case 0x2F://cmd2F[1]
                switchStatusTextView.setText("关闭");
                break;

            case 0x0E://cmd13[1]
                switchStatusTextView.setText("开启");
                break;

            default:
                break;
        }

    }

    public void updateDeviceName(String device_name) {
        // TODO Auto-generated method stub
        findDevicePetName();
        if(device_name !=null) {
            if (myDevicePetName == null) {
                devicePetName.setText(device_name);
            } else {
                devicePetName.setText(myDevicePetName);
            }
        }

    }

}